package com.yuanyi.controller;

import com.alibaba.fastjson.JSONObject;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.yuanyi.dao.TodoDao;
import com.yuanyi.entity.Todo;
import com.yuanyi.util.AccessTokenUtil;
import com.yuanyi.util.NetUtil;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class IndexController {
    @Autowired
    TodoDao todoDao;

    @Autowired
    private Redisson redisson;


    @GetMapping("/todotest")
    public void todotest() {
        // 获取锁对象
        RLock lock = redisson.getLock("Hello");

// 尝试加锁, 默认30秒, 自动后台开一个线程实现锁的续命
        boolean isok = lock.tryLock();
        System.out.println(Thread.currentThread() + "想获得锁");
        if (isok) {
            try {
                System.out.println(Thread.currentThread() + "获得锁成功");
                Todo t = todoDao.findById(1).get();
                if (t.getMoney()!= 0) {
                    System.out.println("抢单失败！");
                    return;
                }

                t.setMoney(1);
                Todo tt = todoDao.save(t);
                if (tt != null) {
                    System.out.println("抢单成功！");
                } else {
                    System.out.println("抢单失败！");
                }
                System.out.println(t.getMoney());
            } finally {
                // 释放锁
                lock.unlock();
                System.out.println(Thread.currentThread() + "释放锁");
            }
        }
    }



    public static void main(String[] args) throws IOException, WriterException, InterruptedException {



      //  zoomPic("c://1111.jpg","c://2222.jpg",0.2);



//        while(true) {
//            for (int i = 1; i <= 10; i++) {
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        NetUtil.post("http://localhost/todotest", "");
//                    }
//                }).start();
//            }
//            Thread.sleep(1000);
//        }
//        Map<EncodeHintType, Object> hints = new HashMap<>();
//        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//        hints.put(EncodeHintType.MARGIN, 0);
//
//        QRCodeWriter qrCodeWriter = new QRCodeWriter();
//        BitMatrix bm = qrCodeWriter.encode("http://www.baidu.com"
//                , BarcodeFormat.QR_CODE, 200, 200, hints);
//        MatrixToImageWriter.writeToStream(bm, "png",
//                new FileOutputStream("c://123.png"));

//        URL url = new URL("https://api.weixin.qq.com/cgi-" +
//                "bin/material/batchget_material?access_token=24_AzzX-ncXZqBGav4V3qUSa3L-" +
//                "URkzIxXD57G9tg9iUp-3x-UhAPdnTMdShjAlb4qXrJP-pYRLg6ujEckdu836-" +
//                "37OQUSYcEOpuHOiPkfwaoPkBi0U52JqC6gCybaXc971BfnBeztO_tnGWsgdDIUaAHAHMY");
//        HttpURLConnection con = (HttpURLConnection) url.openConnection();
//        con.setDoOutput(true);
//        con.setDoInput(true);
//
//        String sendStr = "{\"type\":\"voice\",\"offset\":0,\"count\":1}";
//
//        con.getOutputStream().write(sendStr.getBytes());
//        con.getOutputStream().flush();
//
//        BufferedReader br = new BufferedReader(
//                new InputStreamReader(con.getInputStream(),"utf-8")
//        );
//
//        String str;
//        StringBuffer sb = new StringBuffer();
//        while((str=br.readLine())!=null){
//            sb.append(str);
//        }
//
//        System.out.println(sb);
    }

    @PostMapping("/index")
    public String name(HttpServletRequest req) throws IOException {  //http://sssss/sss?a=1&b=2
        BufferedReader br = new BufferedReader(
                new InputStreamReader(req.getInputStream(), "utf-8")
        );

        String str;
        StringBuffer sb = new StringBuffer();
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }

        br.close();

        String xml = sb.toString();
        //xml ==> obj
        int start = xml.indexOf("CDATA[");
        int end = xml.indexOf("]", start);
        String toUserName = xml.substring(start + 6, end);

        start = xml.indexOf("CDATA[", end);
        end = xml.indexOf("]", start);
        String fromUserName = xml.substring(start + 6, end);

        Date date = new Date();
        String time = (date.getTime() / 1000 + "");

        String media_id = "Tm0wloeelsI3zbVLe4QVx6MKnwbYdqO4HTwNPlIXO9c";
//        return "<xml>\n" +
//                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
//                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
//                "  <CreateTime>"+time+"</CreateTime>\n" +
//                "  <MsgType><![CDATA[text]]></MsgType>\n" +
//                "  <Content><![CDATA[你好厉害！]]></Content>\n" +
//                "</xml>";

        return "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>" + time + "</CreateTime>\n" +
                "  <MsgType><![CDATA[voice]]></MsgType>\n" +
                "  <Voice>\n" +
                "    <MediaId><![CDATA[" + media_id + "]]></MediaId>\n" +
                "  </Voice>\n" +
                "</xml>";
    }

    @GetMapping("/index")
    public String name(String signature, String timestamp, String nonce, String echostr) {
        String[] strs = {"hehe", timestamp, nonce};
        Arrays.sort(strs);

        StringBuilder str = new StringBuilder();
        for (int i = 0; i < strs.length; i++) {
            str.append(strs[i]);
        }

        MessageDigest md = null;
        String tempStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.toString().getBytes());
            tempStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if (signature.toUpperCase().equals(tempStr)) {
            return echostr;
        }

        return "";
    }

    private String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest = strDigest + byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private String byteToHexStr(byte b) {
        char[] digit = {
                '0',
                '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E',
                'F'};

        char[] tempArr = new char[2];
        tempArr[0] = digit[(b >>> 4 & 0xF)];
        tempArr[1] = digit[(b & 0xF)];
        String s = new String(tempArr);
        return s;
    }

    @GetMapping(path = "/add") // Map ONLY POST Requests
    public String addNewUser(@RequestParam String name
            , @RequestParam String content) {
        Todo t = new Todo();
        t.setContent(content);
        t.setCreatedate(new Date() + "");
        t.setName(name);
        todoDao.save(t);
        return "Saved";
    }

    @GetMapping("/find_openid")
    public String find_openid(String code) {
        JSONObject obj = AccessTokenUtil.findWebAccessToken(code);
        return obj.getString("openid");
    }

    @GetMapping(path = "/all")
    public @ResponseBody
    Iterable<Todo> getAllUsers() {
        return todoDao.findAll();
    }
}
